from flask import Blueprint,jsonify,request
from db import db1
from utils.redisconn import r
import json


bp_work = Blueprint('workf',__name__)


@bp_work.route('/workflow')
def workflow():
    sql = "select * from workf"
    res = db1.find_all(sql)
    return jsonify({'code':200,'list':res})


#获取数据源接口
@bp_work.route('/getresourcedata')
def getresourcedata():
    #从redis取，如果有直接返回
    values = r.get_str('dataresouce')
    if values:
        list = eval(values)
    else:
        #如果没有查询
        sql = "select * from data_source"
        res = db1.find_all(sql)
        list = []
        if res:
            for i in res:
                dict={'id':i['id'],'name':i['name']}
                sql1 = "select id,name,type from %s"%(i['tablename'])
                subres = db1.find_all(sql1)
                dict['mes'] = subres
                list.append(dict)
        #存入redis
        r.set_str('dataresouce',json.dumps(list))
    return jsonify({"code":200,'list':list})


@bp_work.route('/updateworkf',methods=['POST','GET'])
def updateworkf():
    if request.method == 'POST':
        res = request.json
        sql = "update workf set params='%s' where id=%d"%(res['params'],int(res['id']))
        db1.update(sql)
        return jsonify({"code":200,'msg':'成功'})
    else:
        pid = request.args.get('id')
        sql = "select * from workf where id=%d"% int(pid)
        res = db1.find(sql)
        return jsonify({'code':200,'list':res})
# [{"lable":"姓名","type":"input","values":"[{"id":1,"name":"事假","type":1},{"id":2,"name":"产假","type":2},{"id":3,"name":"病假","type":3}]"},{"lable":"工号","type":"input"}]

# 审批
@bp_work.route('/examine',methods=['POST'])
def examine():
    data = request.json
    data1 = data['approver'][0]
    print(data1)
    sql1 = "insert into examine (title,params,stutas,approver,next_approver) values ('%s','%s',1,'%s',%d)"%(data['title'],data['params'],json.dumps(data['approver']),int(data1))
    db1.update(sql1)
    sql1 = "select id,title from examine where title='%s'" % (data['title'])
    task = db1.find(sql1)
    # 把当前任务加到redis中，选用hash类型
    key = 'task%d' % (data1)
    r.insert_hash_set(key, task['id'], task['title'])
    return jsonify({'code':200,'msg':'提交成功'})


def getdeptdata(data):
    tree = {}
    list = []
    for i in data:
        tree[i['id']] = i

    for j in data:
        pid = j['pid']
        if not pid:
            j['type'] = 1
            list.append(j)
        else:
            if 'children' not in tree[pid]:
                tree[pid]['children'] = []
            # 查询此部门下所有员工
            sql = "select * from users where dept_id=%d " % (int(j['id']))
            res = db1.find_all(sql)
            userlist = []
            if res:
                for u in res:
                    u['type'] = 3
                    userlist.append(u)
            j['children'] = userlist
            j['type'] = 2
            tree[pid]['children'].append(j)

    return list



@bp_work.route('/getcomanyuser')
def getcomanyuser():
    # 获取所有公司及所有部门
    sql = "select * from dept"
    res = db1.find_all(sql)
    mes = getdeptdata(res)
    return jsonify({'code': 200, 'list': mes})
    # 数据重组，查询员工


#待我审批
@bp_work.route('/mytaskaudit')
def mytaskaudit():
    id = request.args.get('id')
    #从redis中获取我的任务列表
    key='task%d'%(int(id))
    print(key)
    task = r.get_all_hash_params(key)
    list=[]
    for k,v in task.items():
        uid = str(k,encoding='utf8')
        title = str(v,encoding='utf8')
        list.append({'id':uid,'title':title})

    return jsonify({"code":200,'list':list})



@bp_work.route('/examineone')
def examineone():
    eid = request.args.get('eid')
    sql = "select * from examine where id=%d"%int(eid)
    res = db1.find(sql)
    res['params'] = json.loads(res['params'])
    res['approver'] = json.loads(res['approver'])
    # print(type(json.loads(res['approver'])))
    return jsonify({'code':200,'list':res})


@bp_work.route('/dispose',methods=['POST'])
def dispose():
    data = request.json
    sql = "select * from examine where id=%d"%int(data['eid'])
    res = db1.find(sql)
    lis = json.loads(res['approver'])
    sql1 = "update examine set stutas=2,next_approver=%d where id=%d"%(lis[2],int(data['eid']))
    db1.update(sql1)
    # 把当前任务加到redis中，选用hash类型
    key = 'task%d' % (lis[1])
    r.insert_hash_set(key, res['id'], res['title'])
    return jsonify({'code': 200, 'msg': '提交成功'})
